package com.zhijiang.hospital.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhijiang.common.config.result.InsertException;
import com.zhijiang.common.util.Util;
import com.zhijiang.common.util.WxService;
import com.zhijiang.hospital.entrty.*;
import com.zhijiang.hospital.entrty.dto.EmployeeDto;
import com.zhijiang.hospital.mapper.EmployeeDtoMapper;
import com.zhijiang.hospital.mapper.EmpolyeeMapper;
import com.zhijiang.hospital.mapper.ProgressMapper;
import com.zhijiang.hospital.mapper.RepairMapper;
import com.zhijiang.hospital.service.RepairService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RepairServiceImpl implements RepairService {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

    String data1="{\n" +
            "           \"touser\":\"oawgq5tM_jfuTN90_BS_KrOFrZHw\",\n" +
            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
            "           \"data\":{\n" +
            "                   \"first\": {\n" +
            "                       \"value\":\"有个维修申请,请查看!\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword1\":{\n" +
            "                       \"value\":\"信息系统软硬件故障\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword2\": {\n" +
            "                       \"value\":\"现在\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword3\": {\n" +
            "                       \"value\":\"申请科室所在地点\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"remark\":{\n" +
            "                       \"value\":\"尽快抢单！\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   }\n" +
            "           }\n" +
            "       }";
    @Resource
    RepairMapper repairMapper;
    @Resource
    EmployeeDtoMapper employeeDtoMapper;
    @Override
    public List<Repair> selectAll(String startTime, String endTime) {

        List<Repair> list   = repairMapper.selectAllByTime(startTime,endTime);
        list.stream().forEach(s->{
            if (s.getRepairState().equals("1")){
                s.setRepairState("未被接单");
            }else if (s.getRepairState().equals("2")){
                s.setRepairState("未完成");
            }else if (s.getRepairState().equals("3")){
                s.setRepairState("已完成");
            }



        });
        return list;
    }
    String AllOpenId[]={"oawgq5tM_jfuTN90_BS_KrOFrZHw"
            ,"oawgq5lULhXxL865bUoksVWE1t6U",
            "oawgq5sYx3w4ochQu4XzkLfJwds8",
            "oawgq5nvxDKgMjyyGua9qc1bkM2Y",
            "oawgq5nG_hCB2Uk7FeDR6Vkf0Xi4",
            "oawgq5vZWDnSkqCMJ9GJdelm9Vj8",
            "oawgq5vl0RswNgJ3PREV6MTQdUMQ"
    };
    @Override
    public String repairApplication(Repair repair) {

        if (repair.getRepairLeadership().length()>0){
            repair.setRepairLeadership(repair.getRepairLeadership().substring(0,6));
        }
        String maxId = repairMapper.repairSelectMaxId();
        if (StrUtil.isNotBlank(maxId)) {
            String day_base = maxId.substring(0, 8);
            String currDate = DateUtil.format(DateUtil.date(), "yyyyMMdd");
            if (day_base.equals(currDate)){
                String sequese_base = StrUtil.subSuf(maxId,8);
                Integer integer = Integer.valueOf(sequese_base)+1;
                String id=String.format("%4d", integer).replace(" ", "0");
                maxId=day_base+id;
            }else {
                maxId = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "0001";
            }
        } else {
            maxId = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "0001";
        }

        repair.setRepairApplyId(maxId);
        repair.setState("1");
        repair.setRepairState("1");
        //repair.setRepairApplyDate();
        EmployeeDto oneEmployeeDto = employeeDtoMapper.findOneEmployeeDto(repair.getRepairApplyOperator());
        if (StringUtils.isBlank(oneEmployeeDto.getDeptCode())){
            throw new RuntimeException("不是本院员工不能申请");
        }
        repair.setRepairApplyDept(oneEmployeeDto.getDeptCode());

        Integer row = repairMapper.insert(repair);

        Repair repair1 = repairMapper.selectMyRepairOrderById(maxId, "1");
        String repairApplyOperator = repair1.getRepairApplyOperator();
        String repairApplyType = repair1.getRepairApplyType();
        String repairApplyDetail = repair1.getRepairApplyDetail();
        String repairApplyDept = repair1.getRepairApplyDept();
        String repairApplyPhone = repair1.getRepairApplyPhone();

        //通过申请电话获取申请人
        List<Employee> employees = repairMapper.selectEmployee(repairApplyPhone);
        String employeeName = employees.get(0).getEmployeeName();
        //获取申请人科室
        List<Department> departments = repairMapper.selectDepartById(repair.getRepairApplyDept());

        String deptName = departments.get(0).getDeptName();

        if (row != 1) {
            throw new InsertException("插入数据失败");
        }else {
            String url_phone="http://192.168.1.110:8081";
//            //短息发送
            String param_phone="SmsServer.ashx?id=1&" +
                    "phone=18871742296&" +
                    "phone=18608608556&" +
                    "phone=13477837799&" +
                    "phone=13872497873&" +
                    "phone=15072562385&" +
                    "phone=15872485525&" +
                    "phone=18064244115&" +
                    "content=有新的维修申请可以接单:"+employeeName+"||"+deptName+"||"+repairApplyType+"||"+repairApplyDetail+"||"+repairApplyPhone;
            sendGet(url_phone,param_phone);
            //公众号推送
            for(int i=0;i<AllOpenId.length;i++){
                String openId=AllOpenId[i];
                //JSON格式的字符串替换
                JSONObject jsonObj = JSONObject.parseObject(data1);
                String ss = jsonObj.getString("touser");
                data1 = data1.replace(ss,openId);
                //公众号推送消息
                sendTemplateMessage();
            }

        }
return repair.getRepairApplyId();
    }

    @Override
    public Repair selectByRepairApllyid(String repairApplyId) {
        //通过维修号
       Repair repair =  repairMapper.selectByRepairApllyid(repairApplyId);
        return repair;
    }

    @Override
    public List<TImage> selectImageByRepairApllyid(String repairApplyId) {

        return  repairMapper.selectImageByRepairApllyid(repairApplyId);
    }

    @Override
    public List<Repair> selectByToDateRepairAll(String start, String end) {
        return repairMapper.selectByToDateRepairAll(start,end);
    }
    @Resource
    EmpolyeeMapper empolyeeMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void automaticDispatch(List<Repair> repairs, String format, String format1) {

        ArrayList<EmployeeDto> employeeDtos = new ArrayList<>();
        List<DutyTable> dutyTables = repairMapper.selectXxkPaiban1();
        //获取所有员工
        for (DutyTable dutyTable : dutyTables) {
            EmployeeDto employeesByPhone = employeeDtoMapper.findEmployeesByPhone(dutyTable.getPhone());
            employeeDtos.add(employeesByPhone);
        }
        for (EmployeeDto employeeDto : employeeDtos) {
            String weixiu = stringRedisTemplate.opsForList().leftPop("weixiu");
            Repair repair = JSONUtil.toBean(weixiu, Repair.class);
            if (StringUtils.isBlank(repair.getRepairApplyId())){

            }else {
                repairMapper.updateByRepairapplyid(repair.getRepairApplyId(),employeeDto.getEmplCode(),new Date());
                String url_phone="http://192.168.1.110:8081";
                //            //短息发送
                String param_phone="SmsServer.ashx?id=1&" +
                        "phone=" +employeeDto.getREMARK()+
                        "&content=当前有新的订单已自动分派给您:"+employeeDto.getEmplName()+"||"+employeeDto.getDeptName()+"||"+repair.getRepairApplyType()
                        +"||"+repair.getRepairApplyDetail()+"||"+repair.getRepairApplyPhone();
                sendGet(url_phone,param_phone);

            }



        }
        stringRedisTemplate.delete("weixiu");
    }
    @Resource
    ProgressMapper progressMapper;
    @Override
    public List<Progress> selectProgressAllByRepairId(String repairApplyId) {
        //查询相关维修记录
        List<Progress> progresses = progressMapper.selcetAll(repairApplyId);
        return progresses;
    }

    @Override
    public List<String> getList() {
        List<EmployeeDto> employeesByPhone = empolyeeMapper.findList();
        ArrayList<String> strings = new ArrayList<>();
        for (EmployeeDto employeeDto : employeesByPhone) {
            strings.add(employeeDto.getEmplCode()+employeeDto.getEmplName());
        }
        return strings;
    }

    @Override
    public void updateAuto() {
        String weixiu = stringRedisTemplate.opsForList().leftPop("weixiu");
        Repair repair = JSONUtil.toBean(weixiu, Repair.class);
        Repair pRepair = repairMapper.selectByRepairApllyid(repair.getRepairApplyId());
        if (Objects.isNull(pRepair)){

        }else {
            if (pRepair.getRepairState().equals("1")){

                List<DutyTable> dutyTables = repairMapper.selectXxkPaiban1();
                for (DutyTable dutyTable : dutyTables) {

                }

            }else {

            }
        }

    }

    @Override
    public EmployeeDto getEmployee(String emplCode) {
        EmployeeDto oneEmployeeDto = employeeDtoMapper.findOneEmployeeDto(emplCode);
        return oneEmployeeDto;

    }

    @Override
    public List<DutyTable> selectXxkPaiban1() {
        return repairMapper.selectXxkPaiban5();
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "/" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    //微信公众号消息推送
    public void sendTemplateMessage() {
        String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        url=url.replace("ACCESS_TOKEN", WxService.getAccessToken());
        String result= Util.post(url, data1);

    }
}
